<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/Action.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/Response.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/Service.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/const/Error.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/const/Pattern.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/const/Menu.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/utils/Logger.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/utils/Str.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/ServiceFactory.php';

final class LoginAction extends Action {
	protected function accessIdentities() {
		return null;
	}

	protected function execute(Response $response) {
		if(isset($_SESSION['user'])) {
			$response->setActionPath('/logout.html');
		} else {
			if(isset($_POST['login']) && Str::isMatch(Pattern::LOGIN, $_POST['login'])) {
				$login = $_POST['login'];
				$password = '';
				if(isset($_POST['password'])) {
					$password = md5($_POST['password']);
				}
				$serviceFactoy = new ServiceFactory(); // Создаем фабрику сервисов
				$servicePers = $serviceFactoy->getService('PersonService');// Получаем нужный сервис
				$person = $servicePers->authorization($login, $password);// Выполняем нужное действие
				$serviceEmpl = $serviceFactoy->getService('EmployeeService');// Получаем еще один сервис.Он нам нужен для заполнения ролей пользователя

				if($person){
					$posts = $serviceEmpl->getPersonPosts($person);
					foreach($posts as $post) {
						$person->addPost($post);
					}
					$servicePers->fillRoles($person);
				}

				if($person) {
					$_SESSION['user'] = serialize($person);
					$menu = array();
					$menus = Menu::getItems();
					foreach($person->getRoles() as $role) {
						$identity = $role->getIdentity();
						if(isset($menus[$identity])) {
							$menu = array_merge($menu, $menus[$identity]);
						}
					}
					if(count($menu)) {
						$_SESSION['menu'] = serialize($menu);
					}
					$response->setActionPath('/index.html');
					Logger::info('login user "'.$person->getLogin().'"');
				} else {
					$response->setParameter('message', Error::LOGIN_INCORRECT);
					$response->setParameter('login', $login);
				}
			}
		}
	}
}
?>